import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import axios from "axios";
import jwtDecode from 'jwt-decode'

import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'
import {Message} from "element-ui";
// Progress 进度条样式
// 进度条配置项
NProgress.configure({
  showSpinner: false
});

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('../components/Login')
  },
  {
    path: '/index',
    component: () => import('../components/Main')
  },
  {
    name: 'index',
    path: '/index',
    component: () => import('../components/Main'),
    redirect: '/dashboard',
    children: [
      //主页(all)
      {
        path: '/dashboard',
        component: () => import('../components/Dashboard')
      },
    ]
  },
]
const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  NProgress.start();
  const token = window.localStorage.getItem('authorization')
  if (token) {
    const code = jwtDecode(token)
    if (to.path === '/' || code.exp * 1000 < Date.now()) {   //跳转
      if (code.exp * 1000 < Date.now()) {  //跳转登录，检验token是否过期
        window.localStorage.removeItem('authorization')
        next('/')
        Message({
          message: "本次登录已过期，请重新登录",
          type: 'error',
          duration: 5 * 1000
        })
      }
      NProgress.done()
      next()
    } else {
      if (store.state.menuRouteList[0] == '-1') {
        store.dispatch('getPermissions').then(() => {
          store.dispatch('addMenuAndRouter').then(() => {
            next({...to, replace: true}) // hack方法 确保addRoutes已完成
            NProgress.done()
          })
        }).catch(err => {
          NProgress.done()
          next('/')
        })
      } else {
        NProgress.done()
        next()
      }
    }
  } else {
    if (to.path === '/') {
      NProgress.done()
      next()
    } else {
      NProgress.done()
      next('/')
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
});

export default router
